package ua.tach.shortl;

import ua.tach.shortl.logic.Country;

import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

public class RenderCounter {
	public static TextureRegion[] DigitTexture;

	protected int digitPosX;
	protected int digitPosY;
	protected int digitSize;
	private int valIndex;
	protected int curValue;
	protected int moveStep;
	protected int[] oldDigits = {0,0,0,0};
	protected int[] newDigits = {0,0,0,0};

	public RenderCounter() {
	}

	public RenderCounter (int px, int py, int size, int i) {
		digitPosX = px;
		digitPosY = py;
		digitSize = size;
		valIndex = i;
		moveStep = 0;
		curValue = Country.Counters[valIndex]-1;
	}

	public void tick() {
		if (moveStep <= 0) {
			int tmpval = Country.Counters[valIndex];
			if (tmpval >= Math.pow(10, digitSize) )
				tmpval = (int)Math.pow(10, digitSize) - 1;

			if (curValue != tmpval) {
				curValue += (curValue > tmpval)? -1 : 1;
				updateCnt(curValue);
			}
		} else {
			moveStep -= 2;
			if (moveStep <= 0)
				for (int i = digitSize-1; i>=0; --i) {
					oldDigits[i] = newDigits[i];
				}
		}
	}

	protected void updateCnt(int val) {
		int tmpval = (val>0)?val:0;
		for (int i = digitSize-1; i>=0; --i) {
			if (i==0) {
				newDigits[i] = tmpval;
			} else {
				newDigits[i] = tmpval/ (int)Math.pow(10, i);
				tmpval = tmpval % (int)Math.pow(10, i);
			}
		}
		moveStep = TextureLoader.SP_DIGITH;
	}

	public void render( SpriteBatch spriteBatch ) {
		for (int i = digitSize-1; i>=0; --i) {
			if(oldDigits[i] == newDigits[i])
				spriteBatch.draw(DigitTexture[newDigits[i]], digitPosX - i*(TextureLoader.SP_DIGITW), digitPosY);
			else {
				spriteBatch.draw(DigitTexture[oldDigits[i]], digitPosX - i*(TextureLoader.SP_DIGITW),
						digitPosY-TextureLoader.SP_DIGITH+moveStep);
				spriteBatch.draw(DigitTexture[newDigits[i]], digitPosX - i*(TextureLoader.SP_DIGITW),
						digitPosY+moveStep);
			}
		}
	}
}
